<?php

/*

COMP 353F
Dr. B Desai
Final Project
Group #11

6330746 Nicholas CONSTANTINIDIS
9532862 Jacqueline FU
5484537 Claudio Javier LOPEZ FLORES
9218416 Que Tung NGUYEN

*/

  session_start();
?>

<!DOCTYPE html>
<html lang="en">
<head>
        <title>CoBAGSys - Home</title>
        <link type="text/css" rel="stylesheet" href="css/mystyle.css">
        <script type="text/JavaScript" src="js/validate.js"></script>
        <script type="text/JavaScript">
        <!--
        function ValidateFields() {
	        return ValidateFieldNotEmpty("slick-login", "pname", "posting name")
	        && ValidateFieldNotEmpty("slick-login", "price", "price")
	        && ValidateFieldNumeric("slick-login", "price", "price")
	        && ValidateFieldNotEmpty("slick-login", "pcity", "posting city")
	        && ValidateFieldNotEmpty("slick-login", "description", "description");
        }
        //-->
        </script>
</head>
<body>
    <?php
      require 'menus.php';
    ?>
    <?php
		// Upload the given file
		function uploadfile() {
			if (!isset($_FILES["image"]) || $_FILES["image"]["error"] > 0)
			{
				return "";
			}
			else
			{
				if (!file_exists("img/" . $_FILES["image"]["name"]))
					move_uploaded_file($_FILES["image"]["tmp_name"], "img/" . $_FILES["image"]["name"]);
				
				return "./img/" . $_FILES["image"]["name"];
   			}
		}

		// Create the new posting
		function editposting() {
			$db = new Connect();
			
			$imageurl = uploadfile();			
			$pname = $_POST['pname'];
			$price = $_POST['price'];
			$cid = $_POST['cid'];
			$pcity = $_POST['pcity'];
			$dcity = $_POST['dcity'];
			$desc = $_POST['description'];

			// Preserve existing image if blank
			if ($imageurl == "")
				$imageurl = "img";
			else
				$imageurl = "'" . $imageurl . "'";
			
			
			$sql = "UPDATE Posting " .
				   "SET img = " . $imageurl . ", " .
				   "pCity = '" . $pcity . "', " .
				   "displayCity = '" . $dcity . "', " .
				   "pName = '" . $pname . "', " .
				   "pDesc = '" . $desc . "', " .
				   "price = " . $price . ", " .
				   "cID = " . $cid . " " .
				   "WHERE pID = " . $_GET['pid'];
				   
			$result = $db->query($sql);
			
			if(!$result || mysql_affected_rows() == 0) // Failed updating posting
			{
				return false;
			}
			else // Post updated
			{
				// Redirect user to posting
				print "<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=posting.php?pid=" . $_GET['pid'] . "\">";
				
				return true;
			}
		}
		
		function getPosting() {
			$db = new Connect();
			
			$sql = "SELECT img, pCity, displayCity, pName, pDesc, price, cID " .
				   "FROM Posting " .
				   "WHERE pid = " . $_GET['pid'];
				   
			$result = $db->query($sql);
			
			if(!$result || mysql_num_rows($result) == 0) // Couldn't find posting
			{
				return;
			}
			else // Return posting info
			{
				$rows = $db->to_array($result);
				return $rows[0];
			}
		}
		
		function notifyBidders() {
			$db = new Connect();
			
			$sql = "INSERT INTO Notice(mID, pID, tID, nDatetime, subject, body) " .
				   "SELECT mID, pID, tID, now(), 'Posting modified', 'The posting has been modified by the seller.' " .
				   "FROM Transaction " .
				   "INNER JOIN MemberInfo ON MemberInfo.email = Transaction.email " .
				   "WHERE pID = " . $_GET['pid'];

			$result = $db->query($sql);
			
			if(!$result) // Couldn't notify bidders
			{
				return false;
			}
			else // Bidders notified
			{
				return true;
			}
		}
		
		// Check to see if we received post data and perform edit
		// TODO: Check that the information is correct first and check for empty fields
		$posting_failed = false;
		if (isset($_POST["edit"]))
			$posting_failed = !(editposting() && notifyBidders());			
    ?>
    <div id="main">
<?php
    // We need to keep the pid value from disappearing
	print "<form id=\"slick-login\" onsubmit=\"return ValidateFields();\" action=\"editpost.php?pid=" . $_GET['pid'] . "\" method=\"post\" enctype=\"multipart/form-data\">"
?>
	    	<p class="title">
	    		Edit posting
	    	</p>
<?php
	if ($posting_failed == true)
		print "<p></p><span class=\"error\">FAILED TO EDIT POSTING!</span>";

	$posting = getPosting();
	if (isset($posting))
	{
		print "<input type=\"text\" name=\"pname\" placeholder=\"Posting Name\"\" value=\"" . $posting['pName'] . "\"> ";

		$rows = getCategoriesForMenu();
		
		if (isset($rows))
		{
			$rowcount = count($rows);
			print "<span class=\"normal\">Category:</span> <select name=\"cid\">";
			for ($i = 0; $i < $rowcount; $i++)
			{
				if ($rows[$i]['cid'] == $posting['cID'])
					print "<option selected=\"selected\" value=\"" . $rows[$i]['cid'] . "\">" . $rows[$i]['cName'] . "</option>";
				else
					print "<option value=\"" . $rows[$i]['cid'] . "\">" . $rows[$i]['cName'] . "</option>";
			}
			print "</select>";
		}
		
		print "<span class=\"normal\"><br/>Image:</span>";
		print "<input type=\"file\" size=\"44\" name=\"image\" placeholder=\"Image\"> ";
        print "<input type=\"text\" name=\"price\" placeholder=\"Price\" value=\"" . $posting['price'] . "\"> ";
        print "<input type=\"text\" name=\"pcity\" placeholder=\"Posting city\" value=\"" . $posting['pCity'] . "\"> ";
        print "<input type=\"text\" name=\"dcity\" placeholder=\"Display city\" value=\"" . $posting['displayCity'] . "\"> ";
		print "<textarea rows=\"15\" cols=\"58\" name=\"description\" placeholder=\"Description\">" . $posting['pDesc'] . "</textarea>";
		print "<p></p>";
		print "<input type=\"submit\" name=\"edit\" value=\"     Edit    \"/>";
	}
	else
	{
		print "<p></p><span class=\"error\">INVALID POSTING SPECIFIED!</span>";
	}
?>
        </form>
    </div>
</body>
</html>
